package com.leruan.aasimp.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.leruan.aasimp.bean.SaleCarTypeBean;
import com.leruan.aasimp.dao.VendorDao;

public class VendorDaoImpl extends HibernateDaoSupport implements VendorDao{

	public List<String> getVendorList() throws Exception {
		
		Session session = this.getSession();
		String hql = "select distinct vendorName from CarVendorInfo order by vendorName";
		return session.createQuery(hql).list();
	}

	public List<SaleCarTypeBean> getVendor(Map<String, String> map)
			throws Exception {
		
		Session session = this.getSession();
		java.sql.Date startDate  = java.sql.Date.valueOf(map.get("startTime"));
		java.sql.Date endDate  = java.sql.Date.valueOf(map.get("endTime"));
		
		StringBuffer sb = new StringBuffer("select t2.id , count(t2.id) from CarMainInfo t1, CarVendorInfo t2 where t1.vendorId = t2.id and t1.opeTime>=? and t1.opeTime<=? ");
		if(map.get("vendorName") != null)
			sb.append(" and t2.vendorName ='" + map.get("vendorName") + "'");
		
		sb.append(" group by t2.id order by count(t2.id) desc");
		Query query = session.createQuery(sb.toString()).setDate(0, startDate).setDate(1, endDate);
		
		List list = query.list();
		
		List<SaleCarTypeBean> slist = new ArrayList<SaleCarTypeBean>();
		Float total = 0f;
		for(int i = 0;i < list.size(); i++){
			SaleCarTypeBean sBean = new SaleCarTypeBean(); 
			Object[] object = (Object[]) list.get(i);
			sBean.setPlacing(Integer.parseInt(object[0].toString()));
			sBean.setNum(Integer.parseInt(object[1].toString()));
			sBean.setId((i+1)+"");
			total += sBean.getNum();
			slist.add(sBean);
		}
		if(slist.size() == 0)
			return slist;
		String hql = "select vendorName from CarVendorInfo  where id = ?";
		for(SaleCarTypeBean sBean : slist){
			sBean.setScale(sBean.getNum()/total * 100) ;
			Object uniqueResult = session.createQuery(hql).setString(0, sBean.getPlacing()+"").uniqueResult();
			sBean.setName(uniqueResult.toString());
		}
		return slist;
	}

}
